package com.zhongkun.datahome.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhongkun.datahome.service.constant.EntityTypeEnum;
import com.zhongkun.datahome.service.constant.FileTypeEnum;
import com.zhongkun.datahome.service.domain.CommonFile;
import com.zhongkun.datahome.service.repository.CommonFileRepository;
import com.zhongkun.datahome.service.req.cmd.file.SignFileBatchCmd;
import com.zhongkun.datahome.service.req.cmd.file.SignFileCmd;
import com.zhongkun.datahome.service.req.qry.file.SignFileQry;
import com.zhongkun.datahome.service.res.CommonFileVo;
import com.zhongkun.datahome.service.service.ICommonFileService;
import com.zhongkun.datahome.service.service.IFileService;
import com.zhongkun.datahome.service.utils.StreamUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author: lifengsheng
 * @Date: 2025/4/17 17:01
 * @Desc
 */
@Service
public class CommonFileServiceImpl implements ICommonFileService {
    @Resource
    private CommonFileRepository commonFileRepository;

    @Resource
    private IFileService fileService;

    @Override
    public List<CommonFileVo> list(SignFileQry qry) {
        List<CommonFile> list = commonFileRepository.list(new LambdaQueryWrapper<CommonFile>()
                .eq(CommonFile::getEntityId, qry.getHouseId())
                .eq(CommonFile::getEntityType, EntityTypeEnum.SIGN_FILE.getType())
                .orderByDesc(CommonFile::getUpdateTime));
        return list.stream().map(CommonFileVo::convert).collect(Collectors.toList());
    }

    @Override
    public Long add(SignFileCmd cmd) {
        CommonFile commonFile = CommonFile.convertSignFile(cmd.getHouseId(), cmd);
        // 文件大小
        commonFile.setFileSize(fileService.getFileSize(cmd.getFileUrl()));
        commonFileRepository.save(commonFile);
        return commonFile.getId();
    }

    @Override
    public void delete(List<Long> ids) {
        if (CollectionUtils.isNotEmpty(ids)) {
            commonFileRepository.removeBatchByIds(ids);
        }
    }

    @Override
    public void batchSave(SignFileBatchCmd cmd) {
        List<CommonFile> oldFileList = commonFileRepository.list(new LambdaQueryWrapper<CommonFile>()
                .eq(CommonFile::getEntityId, cmd.getHouseId())
                .eq(CommonFile::getEntityType, EntityTypeEnum.SIGN_FILE.getType()));

        if (CollectionUtils.isEmpty(cmd.getSignFileCmdList())) {
            if (CollectionUtils.isNotEmpty(oldFileList)) {
                List<Long> toRemoveIds = oldFileList.stream().map(CommonFile::getId).collect(Collectors.toList());
                commonFileRepository.removeBatchByIds(toRemoveIds);
            }
            return;
        }

        int sort = 0;
        for (SignFileCmd signFileCmd : cmd.getSignFileCmdList()) {
            signFileCmd.setSort(sort++);
        }

        Map<Boolean, List<SignFileCmd>> booleanAddMap = cmd.getSignFileCmdList().stream()
                .collect(Collectors.partitioningBy(item -> Objects.isNull(item.getId())));

        Map<Long, SignFileCmd> toUpdateFileCmdMap = StreamUtil.listToMap(booleanAddMap.get(false), SignFileCmd::getId, e -> e);
        List<CommonFile> toUpdateFileList = new ArrayList<>();
        List<Long> toRemoveIds = new ArrayList<>();

        oldFileList.forEach(oldFile -> {
            if (toUpdateFileCmdMap.containsKey(oldFile.getId())) {
                oldFile.update(toUpdateFileCmdMap.get(oldFile.getId()));
                oldFile.setFileSize(fileService.getFileSize(oldFile.getFileUrl()));
                toUpdateFileList.add(oldFile);
                return;
            }

            toRemoveIds.add(oldFile.getId());
        });

        // 删除
        if (CollectionUtils.isNotEmpty(toRemoveIds)) {
            commonFileRepository.removeBatchByIds(toRemoveIds);
        }

        // 更新
        if (CollectionUtils.isNotEmpty(toUpdateFileList)) {
            commonFileRepository.updateBatchById(toUpdateFileList);
        }

        // 新增
        if (CollectionUtils.isNotEmpty(booleanAddMap.get(true))) {
            // 遍历获取文件大小
            List<CommonFile> toSaveSignFileList = booleanAddMap.get(true).stream()
                    .map(item -> CommonFile.convertSignFile(cmd.getHouseId(), item))
                    .peek(item -> item.setFileSize(fileService.getFileSize(item.getFileUrl())))
                    .collect(Collectors.toList());
            commonFileRepository.saveBatch(toSaveSignFileList);
        }
    }
}
